package com.googlecode.jerato.library.view;

import com.googlecode.jerato.core.Service;
import com.googlecode.jerato.core.view.ViewFunction;
import com.googlecode.jerato.core.view.ViewParameters;
import com.googlecode.jerato.core.view.ViewTransfer;
import com.googlecode.jerato.library.FunctionService;
import com.googlecode.jerato.library.Settings;
import com.googlecode.jerato.library.SystemException;
import com.googlecode.jerato.library.SystemService;
import com.googlecode.jerato.library.view.xml.XmlView;

public class ViewService  implements Service{
	protected Settings _viewSettings;
	protected FunctionService _functionServie;

	public static ViewService getInstance(){
		return (ViewService)SystemService.getInstance().getService("viewService");
	}

	public void shutdown() {
	}

	public void startup() {
		_viewSettings = ViewSettings.getInstance();
		_functionServie = SystemService.getInstance().getFunction();
	}
	
	public void render(String viewUrl, ViewTransfer trans, ViewParameters input, ViewParameters output){
		ViewFunction view = getView(viewUrl);
		view.call(trans, input, output);
	}

	public ViewFunction getView(String viewUrl){
		if(viewUrl == null){
			throw new IllegalArgumentException("path is null");
		}

		String viewClass = _viewSettings.getString(viewUrl);
		if(viewClass == null){
			throw new SystemException("View settings not found. viewUrl='" + viewUrl + "'");
		}

		try{
			_functionServie.get(viewClass);
		}
		catch(SystemException se){
			//ignore
		}
		ViewFunction view = null;
		if(_functionServie.exists(viewClass)){
			view = (ViewFunction)_functionServie.get(viewClass);
		}
		else{
			view = new XmlView(viewClass);
		}
		return view;
	}
	
}
